package com.jf.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.jf.blog.form.LoginForm;
import com.jf.blog.form.vip.VipRegisterForm;
import com.jf.blog.form.vip.VipResetForm;
import com.jf.blog.service.KaptchaService;
import com.jf.blog.service.UserinfoService;
import com.jf.blog.util.*;
import com.jf.blog.util.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "通用模块")
public class CommonController {
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private KaptchaService kaptchaService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResultJson login(@RequestBody LoginForm loginForm) {
        return userinfoService.login(loginForm);
    }

    @PostMapping("/register")
    @ApiOperation("会员注册")
    public ResultJson register(@RequestBody VipRegisterForm form) {
        userinfoService.vipRegister(form);
        return ResultJson.success();
    }

    @GetMapping("/register/send")
    @ApiOperation("注册时发送短信")
    public ResultJson registerSend(String phone) {
        return userinfoService.vipRegisterSendMsg(phone);
    }

    @GetMapping("/forget/send")
    @ApiOperation("忘记密码发送短信")
    public ResultJson forgetSend(String phone) {
        return userinfoService.vipForgetSendMsg(phone);
    }

    @PostMapping("/reset/password")
    @ApiOperation("重置密码")
    public ResultJson resetPassword(@RequestBody VipResetForm form) {
        userinfoService.vipResetPassword(form);
        return ResultJson.success();
    }

    @GetMapping("/send")
    @ApiOperation("短信验证码")
    public ResultJson send(String phone) {
        String code = MyUtils.getMsmCode();
        String result = MSMUtil.mobileQuery(phone, code);
        if (StringUtils.isEmpty(result)) {
            throw new BusinessException("短信发送异常，请稍后再试...");
        }
        JSONObject json = JSONObject.parseObject(result);
        if (json.getInteger("error_code") == 0) {
            String sid = json.getJSONObject("result").getString("sid");
            Map<String, String> map = new HashMap<>();
            map.put("uuid", sid);
            redisTemplate.opsForValue().set(MyConstants.MSM_KEY + sid, code, Duration.ofMinutes(3));
            return ResultJson.success(map);
        }
        return ResultJson.error(json.getString("reason"));
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public ResultJson logout() {
        LoginUtil.logout();
        return ResultJson.success();
    }

    @ApiOperation("图片验证码")
    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response, @RequestParam String uuid) throws IOException {
        response.setDateHeader("Expires", 0L);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        BufferedImage bi = kaptchaService.getKaptcha(uuid);// 获取验证码图片
        ServletOutputStream out = response.getOutputStream();
        /*禁用缓存，可以解决部分同学电脑因为权限问题导致的500错误*/
        ImageIO.setUseCache(false);
        ImageIO.write(bi, "jpg", out);
    }

    @GetMapping("/info")
    @ApiOperation("当前用户信息")
    public ResultJson info() {
        return ResultJson.success(userinfoService.getById(LoginUtil.getLoginUser().getUserinfoId()));
    }
}
